package com.bwf.jdbc;

import com.mysql.jdbc.Driver;

import java.sql.*;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/6/1 9:46
 * @Copyright 博为峰
 */
public class JdbcDemo01 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        query();
//        insert();
//        update();
    }

    private static void update() {
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", "123456");
             Statement statement = connection.createStatement();) {
            int i = statement.executeUpdate("update t_student set salary = 20000 where id = 2");
        } catch (Exception e) {

        }
    }

    private static void insert() {
        Statement statement = null;
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", "123456");
            int n = 1 / 0;
            statement = connection.createStatement();
            //静态 SQL
            int i = statement.executeUpdate("insert into `t_student`(name,sex,birthday,salary,create_time,update_time,class_id) values ('JAVA3', '男', '2022-05-12', '2000', '2022-05-27 11:01:39', '2022-05-27 11:01:42', '2')");
            System.out.println("i = " + i);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    private static void query() throws SQLException {
        //1.加载驱动
//        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", "123456");
        //3.执行SQL
        Statement statement = connection.createStatement();
        //4.结果集
        ResultSet resultSet = statement.executeQuery("select * from t_student");

        while (resultSet.next()) {
            String name = resultSet.getString("name");
            System.out.println(name);
            int salary = resultSet.getInt(5);
            System.out.println("salary = " + salary);
        }
    }
}
